package com.originskyseed.platform.cms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.Cms;
import com.originskyseed.platform.cms.model.CmsRelateIsRead;
import com.originskyseed.platform.cms.model.CmsRelateView;
import com.originskyseed.platform.cms.service.ICmsRelateIsReadService;
import com.originskyseed.platform.cms.service.ICmsRelateViewService;
import com.originskyseed.platform.cms.service.ICmsService;
import com.originskyseed.platform.cms.service.ICmsTypeService;
import com.originskyseed.platform.cms.vo.request.CmsRequestVO;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IParameterConfigureService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 新闻表Controller类（OSI_CMS）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/cms")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class CmsController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmsController.class);

    @DubboReference
    private ICmsService cmsService;

    @DubboReference
    private IDeptService deptService;

    @DubboReference
    private ICmsTypeService cmsTypeService;

    @DubboReference
    private ICmsRelateViewService cmsRelateViewService;

    @DubboReference
    private IUserInfoService userInfoService;

    @DubboReference
    private ICmsRelateIsReadService cmsRelateIsReadService;

    @DubboReference
    private IParameterConfigureService parameterConfigureService;

    /**
     * 三大平台集成 新闻列表分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cmsList.json")
    @RequiredParams(names = {"pageNo", "pageSize", "type"})
    public BaseResponseBody<BasePage<Cms>> cmsList(HttpServletRequest request) {
        BaseResponseBody<BasePage<Cms>> result = null;
        try {
            CmsRequestVO requestVO = this.getParameterBean(CmsRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            String deptId = this.getParameterString("deptId", null);//部门
            BasePage<Cms> page = new BasePage<Cms>(requestVO.getPageNo(), requestVO.getPageSize());
            if (userInfo == null) {
                return new BaseResponseBody<BasePage<Cms>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_NEWSLIST_SUCCESS.getMsg()), page);
            }
            int type = requestVO.getType();//标识是新闻还是公告（1新闻 2通知公告）
            Integer noticeType = requestVO.getNoticeType()==null?0:requestVO.getNoticeType();//标识是小黑板还是全服广播（1全服广播 2公司小黑板）
            Integer isHomePage = requestVO.getIsHomePage();//标识是否首页（0是 1否）
            Boolean isNews = false;
            if (isHomePage != null && isHomePage == 0) {
                if (deptId != null && noticeType == 2) {
                    //校验是不是业务员或者主播层级
                    Dept dept = this.deptService.selectByPrimaryKey(deptId);
                    if(dept == null){ //主播或者业务员
                        requestVO.setObjId(deptId);
                    }else {
                        requestVO.setPostId(deptId);
                    }
                    requestVO.setIsHomePage(0);
                    page = this.cmsService.selectNoticeListByPage(requestVO.toMap(), page);
                } else {
                    if (type == 2)//展示未读的
                    {
                        //page = this.cmsService.selectDeptNoticeListByPage(requestVO.toMap(), page);
                        requestVO.setObjId(userInfo == null ? "" : userInfo.getId());
                        requestVO.setIsRead(2);
                        //logger.info("==selectNoticeListByPage==map=="+requestVO.toMap());
                        page = this.cmsService.selectNoticeListByPage(requestVO.toMap(), page);
                        if (noticeType == 1)//全服广播，管理级查看不改变状态
                        {
                            if (page != null && page.getResults() != null) {
                                List<String> idsList = new ArrayList<>();
                                for (int i = 0; i < page.getResults().size(); i++) {
                                    idsList.add(page.getResults().get(i).getId());
                                }
                                this.cmsRelateIsReadService.updateIsReadByIds(idsList, userInfo.getId());
                            }
                        }

                    }
                    if(type == 1){ //新闻
                        isNews = true;
                    }
                }
            } else {
                if (type == 2)//展示公告
                {
                    if (userInfo.getSourceSys() == 0) {
                        page = this.cmsService.selectListToOpenPlatformByPage(requestVO.toMap(), page);
                    } else {
                        page = this.cmsService.selectNoticeListByPage(requestVO.toMap(), page);
                    }
                }
               else if (type == 1) //新闻
                {
                    isNews = true;
                }
            }
            //新闻
            if(isNews == true&&userInfo.getSourceSys()!=null){
                if (2==userInfo.getSourceSys()) {
                    requestVO.setBelongPlatform("2");
                    requestVO.setIsState(3);//已发布
                    page = this.cmsService.selectListToGeneralizationByPage(requestVO.toMap(), page, userInfo);
                } else if (1==userInfo.getSourceSys()) {
                    requestVO.setBelongPlatform("1");
                    requestVO.setIsState(3);//已发布
                    page = this.cmsService.selectListToGeneralizationByPage(requestVO.toMap(), page, userInfo);
                } else {
                    page = this.cmsService.selectListToOpenPlatformByPage(requestVO.toMap(), page);
                }
            }
            for (Cms cms:page.getResults()) {
                Integer isRead = this.cmsRelateIsReadService.selectIsReadByCmsId(cms.getId(),userInfo.getId());
                if(isRead!=null && isRead==2){
                    cms.setIsRead(2);
                }else {
                    cms.setIsRead(1);
                }
            }
            result = new BaseResponseBody<BasePage<Cms>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_NEWSLIST_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<Cms>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_NEWSLIST_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 小喇叭 展示今天全服广播
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/trumpetList.json")
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<Cms>> trumpetList(HttpServletRequest request) {
        BaseResponseBody<BasePage<Cms>> result = null;
        try {
            CmsRequestVO requestVO = this.getParameterBean(CmsRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            BasePage<Cms> page = new BasePage<Cms>(requestVO.getPageNo(), requestVO.getPageSize());
            requestVO.setObjId(userInfo == null ? "" : userInfo.getId());
            page = this.cmsService.selectTrumpetListByPage(requestVO.toMap(), page);
            result = new BaseResponseBody<BasePage<Cms>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.TRUMPET_LIST_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<Cms>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.TRUMPET_LIST_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }


    /**
     * 新闻详情查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectByCmsId.json")
    @RequiredParams(names = {"id"})//新闻ID
    public BaseResponseBody selectByCmsId(HttpServletRequest request) {
        BaseResponseBody result = null;
        try {
            String id = getParameterString("id", null);//新闻ID
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            Cms cms = this.cmsService.selectByPrimaryKey(id);
            //阅读量统计
            if (cms != null) {
                this.cmsService.updateVistorCount(id);
            }
            //通过公告已读
            if (cms != null && cms.getType() == 2) {
                CmsRelateIsRead cmsRelateIsRead = new CmsRelateIsRead();
                cmsRelateIsRead.setCmsId(id);
                List<CmsRelateIsRead> isReadList = this.cmsRelateIsReadService.selectList(cmsRelateIsRead);
                if (isReadList != null && isReadList.size() > 0) {
                    cms.setIsReadList(isReadList);
                }
                //查看部门人员信息
                CmsRelateView cmsRelateView = new CmsRelateView();
                cmsRelateView.setCmsId(id);
                List<CmsRelateView> cmsRelateViewList = this.cmsRelateViewService.selectList(cmsRelateView);
                if (cmsRelateViewList != null && cmsRelateViewList.size() > 0) {
                    cms.setCmsRelateViewList(cmsRelateViewList);
                }
                //修改已读
                this.cmsRelateIsReadService.updateIsReadByCmsId(id, userInfo.getId());
            }
            result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), cms);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

	/**
	 * 保存信息_新增新闻_OW 运管
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsSave.json")
	@RequiredParams(names = { "type" })
	public BaseResponseBody<Cms> cmsSave(HttpServletRequest request) {
		BaseResponseBody<Cms> result = null;
		try {
			// 请求对象
			Cms cms = this.getParameterBean(Cms.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 通知公告范围
			// List<Dept> DeptList = this.getParameterList(request,"DeptList",Dept.class);
			if (StringUtils.isNotBlank(cms.getId())) {
				this.cmsService.updateByPrimaryKeySelective(cms);
			} else {
				this.cmsService.insertCmsSelective(cms, userInfo);
			}
			result = new BaseResponseBody<Cms>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_SAVE_SUCCESS.getMsg()), cms);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Cms>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

    /**
     * 删除信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cmsDelete.json")
    @RequiredParams(names = {"ids"})
    public BaseResponseBody<Boolean> cmsDelete(HttpServletRequest request) {
        BaseResponseBody<Boolean> result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});
            this.cmsService.deleteByPrimaryKeys(Arrays.asList(ids));
            result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_DELETE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_DELETE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 批量删除-假删除
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteNewsByIds.json")
    public BaseResponseBody deleteNewsByIds(HttpServletRequest request) {
        BaseResponseBody result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});
            this.cmsService.deleteNewsByIds(Arrays.asList(ids));
            result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_DELETE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_DELETE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 批量修改_下架、发布
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateNewsStateByIds.json")
    @RequiredParams(names = {"ids", "state"})
    public BaseResponseBody updateNewsStateByIds(HttpServletRequest request) {
        BaseResponseBody result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});
            Integer state = this.getParameterInteger("state", null);
            List<String> idsList = Arrays.asList(ids);
            this.cmsService.updateNewsStateByIds(idsList, state);
            //发布，修改通过为已读
            if (state == 3) {
                this.cmsService.updateInformStatusByIds(idsList);
            }
            result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 是否置顶
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateIsTop.json")
    @RequiredParams(names = {"id"}) //新闻ID
    public BaseResponseBody updateIsTop(HttpServletRequest request) {
        BaseResponseBody result = null;
        try {
            String id = this.getParameterString("id", null);
            Cms cms = new Cms();
            cms.setId(id);
            cms.setIsTop(1);
            cms.setUpdateTime(new Date());
            this.cmsService.updateIsTop(cms);
            result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 根据新闻ID，优先级自定义升序、降序
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUpOrDown.json")
    @RequiredParams(names = {"id", "upOrDown"})
    public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
        BaseResponseBody result = null;
        try {
            // 请求参数
            String id = this.getParameterString("id", null);
            Integer upOrDown = this.getParameterInteger("upOrDown", null);
            //获取当前的优先级
            Cms selectByPrimaryKey = this.cmsService.selectByPrimaryKey(id);
            Integer currentPrority = selectByPrimaryKey.getPrority();
            Integer updatePrority = currentPrority;

            // 等于0是升序 1是降序
            if (upOrDown == 0) {
                currentPrority += 1;
            } else {
                currentPrority -= 1;
            }

            // 将另外一个升序或降序
            Cms cms = this.cmsService.selectCmsByPrority(currentPrority);
            if (cms != null) {
                cms.setPrority(updatePrority);
            }
            Cms updateCms = new Cms();
            updateCms.setId(id);
            updateCms.setPrority(currentPrority);
            if (cms != null) {
                this.cmsService.updatePrority(cms, updateCms);
            } else {
                this.cmsService.updateByPrimaryKeySelective(updateCms);
            }

            result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.UPDATE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 查询组织下的部门
     *
     * @param code
     * @param list
     * @throws Exception
     */
    private void selectSonId(String code, List<String> list) throws Exception {
        List<Dept> deptList = this.deptService.selectByParentCode(code);
        if (deptList.size() == 0) {
            Dept dept = this.deptService.selectByCode(code);
            list.add(dept.getId());
            return;
        } else {
            for (Dept dept1 : deptList) {
                list.add(dept1.getId());
                selectSonId(dept1.getCode(), list);
            }
        }
    }

    /**
     * 删除重复项
     *
     * @param list
     * @return
     */
    private List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


}
